var express = require('express');
var router = express.Router();
var fs = require('fs');
var multer = require("multer");
var path = require("path");

var AipFace = require("baidu-ai").face;

var APP_ID = "9968458";
var API_KEY = "IeItj8rupkfKiKHbuiM7y1Ku";
var SECRET_KEY = "Bxt815aWB0dGsGhPsugVrrWxHiB40aq9";
//这三个key记得替换为你申请的appid 

var client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

var faces = require('../db/data/faces.json');

// handle upload storage strategy
var upload = multer({
	storage: multer.diskStorage({
		destination: function(req, file, cb) { // set upload directory
			cb(null, 'public/uploads/face/');
		},
		filename: function(req, file, cb) { // set upload filename
			cb(null, Date.now() + path.extname(file.originalname));
		}
	})
});

/* GET users listing. */
router.get('/', function(req, res, next) {
	var face = faces[parseInt(Math.random() * faces.length)]
	res.render('face/index', {
		sub_title: 'Face',
		face: face
	});
});

router.post('/upload', upload.single('photo'), function(req, res, next) {
	var image = fs.readFileSync(req.file.path);
	var base64Img = new Buffer(image).toString('base64');

	client.detect(base64Img).then(function(result) {
		res.send(JSON.stringify(result));
	});
});

module.exports = router;